<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use api\ServerResponse;
// 应用公共文件
define('MCRYPT_RIJNDAEL_128', "rijndael-128");
define('MCRYPT_MODE_CBC', "cbc");
/*
 * const IMAGETYPE_GIF = 1;
 * const IMAGETYPE_JPEG = 2;
 * const IMAGETYPE_PNG = 3;
 * const IMAGETYPE_SWF = 4;
 * const IMAGETYPE_PSD = 5;
 * const IMAGETYPE_BMP = 6;
 * const IMAGETYPE_TIFF_II = 7;//（Intel 字节顺序）
 * const IMAGETYPE_TIFF_MM = 8;//（Motorola 字节顺序）
 * const IMAGETYPE_JPC = 9;
 * const IMAGETYPE_JP2 = 10;
 * const IMAGETYPE_JPX = 11;
 * const IMAGETYPE_JB2 = 12;
 * const IMAGETYPE_SWC = 13;
 * const IMAGETYPE_IFF = 14;
 * const IMAGETYPE_WBMP = 15;
 * const IMAGETYPE_XBM = 16;
 */
/**
 * aes方式加密处理
 * @param $key string
 */
function encode($key, $data) {
	$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
	$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
	$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
	return strtr(base64_encode($iv . $ciphertext), '+/=', '-*_');
}
/**
 * aes方式解密处理
 */
function decode($key, $data) {
	$data = base64_decode(strtr($data, '-*_', '+/='));
	$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
	$iv = substr($data, 0, $iv_size);
	$pher = substr($data, $iv_size);
	return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $pher, MCRYPT_MODE_CBC, $iv));
}
// 常用的公共函数方法
/**
 * 验证手机号方法
 * @param number $mobile
 * @return boolean
 */
function is_tel($mobile) {
	return strlen($mobile) === 11 && preg_match('/^1[3|4|5|7|8|9]\d{9}$/', $mobile);
}
/**
 * 判断email格式是否正确
 * @param $email
 */
function is_email($email) {
	return strlen($email) > 6 && preg_match('/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/', $email);
}
/**
 * 判断是否是身份证号
 * @param string $card_no
 * @return boolean
 */
function is_card_no($card_no) {
	$vCity = array('11','12','13','14','15','21','22','23','31','32','33','34','35','36','37','41','42','43','44','45','46','50','51','52','53','54','61','62','63','64','65','71','81','82','91');
	if(!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $card_no)) {
		return false;
	}
	if(!in_array(substr($card_no, 0, 2), $vCity)) {
		return false;
	}
	$card_no = preg_replace('/[xX]$/i', 'a', $card_no);
	$vLength = strlen($card_no);
	if($vLength == 18) {
		$vBirthday = substr($card_no, 6, 4) . '-' . substr($card_no, 10, 2) . '-' . substr($card_no, 12, 2);
	} else {
		$vBirthday = '19' . substr($card_no, 6, 2) . '-' . substr($card_no, 8, 2) . '-' . substr($card_no, 10, 2);
	}
	if(date('Y-m-d', strtotime($vBirthday)) != $vBirthday) {
		return false;
	}
	if($vLength == 18) {
		$vSum = 0;
		for($i = 17; $i >= 0; $i--) {
			$vSubStr = substr($card_no, 17 - $i, 1);
			$vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
		}
		if($vSum % 11 != 1) {
			return false;
		}
	}
	return true;
}
/**
 * 判断是否手机访问
 * @return boolean
 */
function isMobileCall() {
	if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
		return true;
	}
	if(isset($_SERVER['HTTP_VIA'])) {
		return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
	}
	if(isset($_SERVER['HTTP_USER_AGENT'])) {
		$client = array('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile');
		$client = join('|', $client);
		if(preg_match("/({$client})/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
			return true;
		}
	}
	if(isset($_SERVER['HTTP_ACCEPT'])) {
		if((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
			return true;
		}
	}
	return false;
}
/**
 * 格式化日期输出
 * @param int $time
 * @param string $formats 格式
 * @return string
 */
function format_time($time, $formats = 'Y/n/j H:i') {
	if(empty($time)) {
		return 0;
	}
	$when = $_SERVER['REQUEST_TIME'] - $time;
	if($when >= 0) {
		$days1 = '-1 day';
		$days2 = '-2 day';
		$format = ['2days'=>'前天 H:i','1days'=>'昨天 H:i','today'=>'今天 H:i','hours'=>'小时前','minutes'=>'分钟前','seconds'=>'秒前'];
	} else {
		$when = -$when;
		$days1 = '1 day';
		$days2 = '2 day';
		$format = ['2days'=>'后天 H:i','1days'=>'明天 H:i','today'=>'今天 H:i','hours'=>'小时后','minutes'=>'分钟后','seconds'=>'秒后'];
	}
	if($when < 60) {
		$what = $format['seconds'];
	} else if($when < 3600) {
		$when = round($when / 60);
		$what = $format['minutes'];
	} else if($when <= 14400) {
		$when = round($when / 3600);
		$what = $format['hours'];
	} else {
		$when = null;
		$date = date('Ymd', $time);
		if($date === date('Ymd')) {
			$what = date($format['today'], $time);
		} else if($date === date('Ymd', strtotime($days1))) {
			$what = date($format['1days'], $time);
		} else if($date === date('Ymd', strtotime($days2))) {
			$what = date($format['2days'], $time);
		} else {
			$what = date($formats, $time);
		}
	}
	return "{$when}{$what}";
}
/**
 * 计算时间月份差
 * @param int $start_time 开始时间戳
 * @param int $end_time 结束时间戳
 * @return $diff, 大于0 过了$diff个月, 小于0则说明时间超前 $diff个月
 */
function diff_month($start_time, $end_time = null) {
	$time1 = date('Y-m', $start_time);
	list($y1, $m1) = explode('-', $time1);
	$time2 = date('Y-m', $end_time ?  : time());
	list($y2, $m2) = explode('-', $time2);
	return ($y2 * 12 + $m2) - ($y1 * 12 + $m1);
}
/**
 * 密码加密
 * @param string $str
 * @param string $salt
 * @return string
 */
function passwd($str, $salt) {
	return sha1(md5($str) . $salt);
}

/**
 * 以json格式输出一段信息
 * @param int $errcode
 * @param message $errmsg
 * @param string|array $str
 * @param string json
 */
function exitJson($errcode, $errmsg, $str = '') {
	return json_encode(['errcode'=>$errcode,'errmsg'=>$errmsg,'str'=>$str], JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES);
}

/**
 * 以数组形式返回
 * @param int $errcode
 * @param message $errmsg
 * @param string $str
 * @return array
 */
function returnArray($errcode, $errmsg, $str = '') {
	return array('errcode'=>$errcode,'errmsg'=>$errmsg,'str'=>$str);
}

/**
 * 判断username格式是否正确
 * 匹配中文,数字, 字母, 下划线
 * @param $username
 */
function is_username($username) {
	$charset = CHARSET;
	if(strtolower($charset) == 'utf-8') {
		$patten = '/^[\x{4e00}-\x{9fa5}_\w]+$/u';
	} else {
		$patten = '/^[' . chr(0xa1) . '-' . chr(0xff) . 'A-Za-z0-9_]+$/';
	}
	return preg_match($patten, $username) && !preg_match('/^[_]+$/u', $username);
}
/**
 * 判断用户名是否合法
 *
 * 只能以数字、字母、中文、下划线构成，并且不能以数字开头
 * @param string $username 用户名
 * @param int $length 用户名最大长度
 * @return true
 */
function checkUserName($username, $length = 16) {
	$return = ['errcode'=>0,'errmsg'=>''];
	if(mb_strlen($username, 'utf-8') < 5 || mb_strlen($username, 'utf-8') > $length) {
		$return['errcode'] = 1;
		$return['errmsg'] = '用户名长度在5-' . $length . '位';
		return $return;
	}
	// 不能以数字下划线开头
	if(preg_match("/^[0-9_]/u", $username)) {
		$return['errcode'] = 2;
		$return['errmsg'] = '用户名不能以数字或下划线开头';
		return $return;
		return false;
	}
	if(!preg_match("/^[\x{4e00}-\x{9fa5}\w]{2,$length}$/u", $username)) {
		$return['errcode'] = 3;
		$return['errmsg'] = '用户名只支持[汉字|字母|数字|下划线]';
		return $return;
	}
	return $return;
}

/**
 * 图片删除（单张或多张）
 * @param array|string $param
 * 如果为字符串时，以英文[逗号]隔开
 */
function del_img($param) {
	if(empty($param)) {
		return returnArray(4, '图片地址为空');
	}
	if(is_array($param) === false) {
		$param = explode(',', $param);
	}
	// 检查文件或目录是否存在
	foreach($param as $k => $v) {
		if(file_exists(substr($v, 1)) === false) {
			$file_err[] = $v;
		}
	}
	if(isset($file_err)) {
		$file_err = implode(',', $file_err);
		if($file_err) {
			return returnArray(2, '未找到图片或者已经删除', $file_err);
		}
	}
	foreach($param as $k => $v) {
		if(unlink(substr($v, 1)) === false) {
			$err_img[] = $v;
		}
	}
	if(isset($err_img)) {
		$err_img = implode(',', $err_img);
		return returnArray(1, '无法找到图片或者已经删除', $err_img);
	}
	return returnArray(0, '图片删除成功', implode(',', $param));
}
/**
 * 随机生成随机数,不足位数的以0补充
 * 默认为6位随机数
 * @param 最小数字 $min
 * @param 最大数 $max
 * @param 生成几位的随机数 $num
 */
function rand_num($min = 0, $max = 999999, $num = 6) {
	return str_pad(mt_rand($min, $max), $num, "0", STR_PAD_BOTH);
}
/**
 * 产生随机数
 * @param length $length
 * @param number $numeric
 * @param string $chars
 */
function random($length, $numeric = 0, $chars = '') {
	$hash = '';
	if(empty($chars)) {
		$chars = base_convert(md5(microtime(1) . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
		$chars = $numeric ? (str_replace('0', '', $chars) . '012340567890') : ($chars . 'zZ' . strtolower($chars));
	}
	$max = strlen($chars) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $chars[mt_rand(0, $max)];
	}
	return $hash;
}
// 为特殊字符添加反斜杠
function daddslashes($string, $strip = false) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = daddslashes($val, $strip);
		}
	} else {
		$string = addslashes($strip ? stripslashes($string) : $string);
	}
	return $string;
}
// 删除addslashes添加的反斜杠
function dstripslashes($string) {
	if(empty($string)) {
		return $string;
	}
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dstripslashes($val);
		}
	} else if((trim($string, '[]{}') !== $string) && strpos($string, '\\')) {
		$json = json_decode($string, true);
		if((json_last_error() == JSON_ERROR_NONE)) {
			$json = dstripslashes($json);
			$string = json_encode($json, JSON_UNESCAPED_UNICODE);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}
// 获取客户端机器ip
function getIp() {
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$ip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$ip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches[0] : '';
}
/**
 * 加密解密函数
 * @param string string
 * 要加密的字符串
 * @param int operation
 * [ 1{加密}, 0{解密} ]
 * @return the secret or string
 */
function auth($string, $operation = 1, $key = null, $expiry = 0) {
	$operation = $operation == 1 ? 'ENCODE' : 'DECODE';
	$auth = \think\Config::get('auth');
	$key = md5($key ? $key : $auth['secret']);
	if($auth['type'] === 'aes') {
		return ($operation === 'ENCODE') ? encode($key, $string) : decode($key, $string);
	} else {
		$keya = sha1(substr($key, 0, 20));
		$keyb = sha1(substr($key, 20, 20));
		$ckey_length = 4;
		$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(sha1(microtime()), -$ckey_length)) : '';
		$cryptkey = $keya . sha1($keya . $keyc);
		$key_length = strlen($cryptkey);
		$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(sha1($string . $keyb), 0, 20) . $string;
		$string_length = strlen($string);
		$result = '';
		$box = range(0, 239);
		$rndkey = array();
		for($i = 0; $i <= 239; $i++) {
			$rndkey[$i] = ord($cryptkey[$i % $key_length]);
		}
		for($j = $i = 0; $i < 240; $i++) {
			$j = ($j + $box[$i] + $rndkey[$i]) % 240;
			$tmp = $box[$i];
			$box[$i] = $box[$j];
			$box[$j] = $tmp;
		}
		for($a = $j = $i = 0; $i < $string_length; $i++) {
			$a = ($a + 1) % 240;
			$j = ($j + $box[$a]) % 240;
			$tmp = $box[$a];
			$box[$a] = $box[$j];
			$box[$j] = $tmp;
			$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 240]));
		}
		if($operation == 'DECODE') {
			if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 20) == substr(sha1(substr($result, 30) . $keyb), 0, 20)) {
				return substr($result, 30);
			} else {
				return '';
			}
		} else {
			return $keyc . str_replace('=', '', base64_encode($result));
		}
	}
}
/**
 * 遍历目录下的文件
 * @param string $dir
 * 要遍历的目录
 * @param string $exts
 * 需要遍历的文件扩展名, [ php | txt | html ]
 * @param bool $is_recursion 是否递归子目录
 * @return boolean | $list
 */
function get_dir_file($dir, $exts = null, $is_recursion = true) {
	if(empty($dir)) {
		return false;
	}
	$dir = rtrim($dir, '/');
	$files = glob($dir . '/*');
	if(empty($files)) {
		return false;
	}
	$list = [];
	foreach($files as $v) {
		$p = pathinfo($v);
		(empty($exts) || $p['extension'] === $exts) && $list[$v] = $p['basename'];
		if($is_recursion && is_dir($v)) {
			$dirfile = get_dir_file($v, $exts, $is_recursion);
			empty($dirfile) or $list += $dirfile;
		}
	}
	return $list;
}
/**
 * 判断文件目录是否为空
 * @param string $dir  文件目录
 * @return boolean
 */
function dir_is_empty($dir){
	dump($dir);
	$handle='';
	if($handle = opendir($dir)){
		while($item = readdir($handle)){
			if($item != '.' && $item != '..'){
				return false;
			}
		}
	}
	return true;
}

/**
 * 检测是否为真实图片
 * @param 上传图片路径，从根目录起  $imgs
 */
function is_imgs($imgs) {
	// $imgs = 'http://'.$_SERVER['HTTP_HOST'].$imgs;
	$mimetype = getimagesize($imgs)[2];
	if($mimetype == IMAGETYPE_GIF || $mimetype == IMAGETYPE_JPEG || $mimetype == IMAGETYPE_PNG || $mimetype == IMAGETYPE_BMP) {
		return true;
	} else {
		return false;
	}
	return false;
}
/**
 * 操作记录写入文件
 * @param string $username
 * @param string $content
 */
function admin_log($username = null, $content = null) {
	header("Content-type: text/html; charset=utf-8");
	// 网站根目录
	$path = './../';
	// 创建文件夹
	$upload = 'runtime/member_log/';
	$path .= $upload;
	if(!file_exists($path)) {
		mkdir($path);
	}
	//以日期写入文件名
	$filename = $path . date('Y-m-d') . '.txt';
	$filename = iconv('UTF-8', 'GB18030', $filename);
	$Ts = fopen($filename, "a+");
	fputs($Ts, date('Y-m-d H:i:s', time()) . ',' . $username . ',' . $content . "\r\n");
	fclose($Ts);
}
/**
 * 数组分页
 * @param array $new_arr
 * @param number $count
 * 每页显示的条数
 * @param number $page
 * 当前页
 * @param string $url
 * 当前url
 * @return string
 */
function array_page(array $arr = null, $count = 0, $page = 1, $url=null){
	if(is_array($arr)===false){
		return false;
	}
	$pamount = sizeof($arr); // 获取数组大小
	$total_page = ceil($pamount / $count); // 最大页码
	//上下页
	$prev = ($page>1)?($page-1):1 ;
	$next = ($page<$total_page)?($page+1):$total_page;
	//中间的几页
	$center = 5;
	$c = floor($center/2);
	$start=$page-$c; //开始页码
	$end=$page+$c;	  //结束页码
	//假如页数不够5页
	if($total_page<$center){
		$start=1;
		$end= $total_page;
	}elseif($start<=0){
		$start=1;
		$end=$center;
	}elseif($end >$total_page){
		$start=$total_page-$center+1;
		$end=$total_page;
	}
	$strpage=$new_arr='';
	if($pamount > $count) {
		$strpage = '<ul class="strpage">%s</ul>';
		$li = '';
		if($page == 1){
			$li .= '<li class="disabled"><span>首页</span></li>';
			$li .= '<li class="disabled"><span>上一页</span></li>';
		}else{
			$li .= '<li><a href="'.str_replace('PAGE', '1', $url).'">首页</a></li>';
			$li .= '<li><a href="'.str_replace('PAGE', $prev, $url).'">上一页</a></li>';
		}
		/**可以去掉**/
		if($page > 4){
			$li .= '<li><a href="'.str_replace('PAGE', '1', $url).'">1...</a></li>';
		}
		/****/
		for($i = $start; $i <= $end; $i++) {
			if($page == $i) {
				$li .= '<li class="active"><span>'.($i).'</span></li>';
			}else{
				$li .= '<li><a href="'.str_replace('PAGE', $i, $url).'">'.$i.'</a></li>';
			}
		}
		/**可以去掉**/
		if($page < ($total_page - 3)){
			$li .= '<li><a href="'.str_replace('PAGE', $total_page, $url).'">...'.$total_page.'</a></li>';
		}
		/****/
		if($page == $total_page){
			$li .= '<li class="disabled"><span>下一页</span></li>';
			$li .= '<li class="disabled"><span>末页</span></li>';
		}else{
			$li .= '<li><a href="'.str_replace('PAGE', $next, $url).'">下一页</a></li>';
			$li .= '<li><a href="'.str_replace('PAGE', $total_page, $url).'">末页</a></li>';
		}
		$li .= '<li class="disabled"><span>第'.$page.'页/共'.$total_page.'页&emsp;共'.$pamount.'条记录</span></li>';
		$strpage = sprintf($strpage,$li);
		$new_arr = array_slice($arr, ($page - 1) * $count, $count);
	}else{
		$new_arr = $arr;
	}
	return  [$strpage,$new_arr];
}
/**
 * 分页
 */
function get_page($page, $perpage) {
	$page = $page > 1 ? $page : 1;
	return ($perpage < 1) ? 0 : [($page - 1) * $perpage,$perpage];
}


use \Firebase\JWT\JWT;

/**
 * [getToken 获取Token加密字符串]
 * @param  [type] $uid [description]
 * @return [type]      [description]
 */
function getToken($uid)
{
    $key = config('jwt.key');  //这里是自定义的一个随机字串，应该写在config文件中的，解密时也会用，相当    于加密中常用的 盐  salt
    $token = [
        "iss"=> config('jwt.iss'),  //签发者 可以为空
        "aud"=> config('jwt.aud'), //面象的用户，可以为空
        "iat" => time(), //签发时间
        "nbf" => config('jwt.nbf'), //在什么时候jwt开始生效  （这里表示生成100秒后才生效）
        "exp" => time()+config('jwt.exp'), //token 过期时间
        "uid" => $uid //记录的userid的信息，这里是自已添加上去的，如果有其它信息，可以再添加数组的键值对
    ];
    $jwt = JWT::encode($token,$key,"HS256"); //根据参数生成了 token
	return $jwt;

}

/**
 * [check Token验证]
 * @param  [type] $jwt [description]
 * @return [type]      [description]
 */
function checkToken($jwt){
    // $jwt = input("token");  //上一步中返回给用户的token
    try {
        $key = config('jwt.key');  //上一个方法中的 $key 本应该配置在 config文件中的
        $info = JWT::decode($jwt,$key,["HS256"]); //解密jwt
    } catch (\Exception $e) {
        return ServerResponse::createByError($e->getMessage());
    }
    return $info;
}



/**
* php完美实现下载远程图片保存到本地
* @param: 文件url,保存文件目录,保存文件名称，使用的下载方式	当保存文件名称为空时则使用远程文件原来的名称
* @date: 2017-05-13
*/
function getimage($url,$save_dir='',$filename='',$type=0){
	if(trim($url)==''){
		return array('file_name'=>'','save_path'=>'','error'=>1);
	}
	if(trim($save_dir)==''){
		$save_dir='./';
	}
	if(trim($filename)==''){//保存文件名
		$ext=strrchr($url,'.');
		if($ext!='.gif'&&$ext!='.jpg'){
			return array('file_name'=>'','save_path'=>'','error'=>3);
		}
		$filename=time().$ext;
	}
	if(0!==strrpos($save_dir,'/')){
		$save_dir.='/';
	}
	//创建保存目录
	if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
		return array('file_name'=>'','save_path'=>'','error'=>5);
	}

	//获取远程文件所采用的方法
	if($type){
		$ch=curl_init();
		$timeout=5;
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
		$img=curl_exec($ch);
		curl_close($ch);

	}else{
		ob_start();
		readfile($url);
		$img=ob_get_contents();
		ob_end_clean();
	}
	//$size=strlen($img);
	//文件大小

	$fp2=@fopen($save_dir.$filename,'a');
	fwrite($fp2,$img);
	fclose($fp2);
	unset($img,$url);
	return array('file_name'=>$filename,'save_path'=>substr($save_dir,1).$filename,'error'=>0);
}
